var delAdids;
$(document).ready(function () {
    var ctx = $('#ctx').val();

    $('#dialog_content select').select2();
    /***************************    读取保存的session数据    ***************************/
    if (typeof (parent.mediaObj2) != "undefined") {
        var mediaObj2 = parent.mediaObj2;
        $('#mediaTable tbody').empty();
        for (var i = 0; i < mediaObj2.adids.length; i++) {
            $('#mediaTable tbody').append(
                '<tr class="tbodyTr"><td class="tbodyTd" style="width:5%;"><div class="checkboxStyleTd"></div></td>'
                + '<td class="tbodyTd" style="width:5%;">' + mediaObj2.adids[i] + '</td>'
                + '<td class="tbodyTd" style="width:30%;" id="websiteName">' + mediaObj2.websiteName[i] + '</td>'
                + '<td class="tbodyTd" style="width:30%;" id="adName">' + mediaObj2.adName[i] + '</td>'
                + '<td class="tbodyTd" style="width:30%;" id="price">' + mediaObj2.price[i] + '</td>'
                + '<input type="hidden" id="adid" value="' + mediaObj2.adids[i] + '" />'
                + '</tr>');
        }
    }
    if (typeof (parent.adxObj2) != "undefined") {
        var adxObj2 = parent.adxObj2;
        $('#adxTable tbody').empty();
        for (var i = 0; i < adxObj2.adids.length; i++) {
            $('#adxTable tbody').append(
                '<tr class="tbodyTr"><td class="tbodyTd" style="width:5%;"><div class="checkboxStyleTd"></div></td>'
                + '<td class="tbodyTd" style="width:5%;">' + adxObj2.adids[i] + '</td>'
                + '<td class="tbodyTd" style="width:30%;" id="appName">' + adxObj2.mediaName[i] + '</td>'
                + '<td class="tbodyTd" style="width:30%;" id="adName">' + adxObj2.adname[i] + '</td>'
                + '<td class="tbodyTd" style="width:30%;" id="price">' + adxObj2.price[i] + '</td>'
                + '<input type="hidden" id="adid" value="' + adxObj2.adids[i] + '" />'
                + '</tr>');
        }
    }
    /***************************    选择媒体    ***************************/
    $(".selectOperator_save").click(function () {
        delAdids = [];
        var adids = [];
        var websiteName = [];
        var adName = [];
        var price = [];
        var mediaObj = {};
        var mediaObj2 = {};
        $('#mediaTable > tbody > tr').each(function () {
            adids.push($(this).find("[id=adid]").val());
            websiteName.push($(this).find("[id=websiteName]").html());
            adName.push($(this).find("[id=adName]").html());
            price.push($(this).find("[id=price]").html());
        });
        if (adids.length > (unique(adids)).length) {
            alert('请勿重复设置广告位');
            return;
        }
        mediaObj.adids = adids;
        mediaObj.delAdids = delAdids;
        mediaObj2.adids = adids;
        mediaObj2.websiteName = websiteName;
        mediaObj2.adName = adName;
        mediaObj2.price = price;
        parent.$("#mediaObj").val(JSON.stringify(mediaObj));
        parent.mediaObj2 = mediaObj2;
        //close dialog
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index);//再执行关闭
    });

    $(".selectAdx_save").click(function () {
        var mediaObj = {};
        delAdids = [];
        var adids = [];
        var appName = [];
        var adName = [];
        var price = [];
        var adxObj = {};
        var adxObj2 = {};
        $('#adxTable > tbody > tr').each(function () {
            adids.push($(this).find("[id=adid]").val());
            appName.push($(this).find("[id=appName]").html());
            adName.push($(this).find("[id=adName]").html());
            price.push($(this).find("[id=price]").html());
        });
        if (adids.length > (unique(adids)).length) {
            alert('请勿重复设置广告位');
            return;
        }
        adxObj.adids = adids;
        adxObj.delAdids = delAdids;
        adxObj2.adids = adids;
        adxObj2.appName = appName;
        adxObj2.adName = adName;
        adxObj2.price = price;
        parent.$("#adxObj").val(JSON.stringify(adxObj));
        parent.adxObj2 = adxObj2;
        //close dialog
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index);//再执行关闭
    });

    $('#mediaDel').click(function () {
        delAdids = [];
        $('#mediaTable > tbody > tr').each(function () {
            var changeClass = $(this).children('td').children('div').attr('class');
            if (changeClass.indexOf('checkboxStyle_change') != -1) {
                //remove td element in tbody
                delAdids.push($(this).find("input[id='adid']").val());
                $(this).remove();
            }
        });
        return false;
    });

    $('#adxDel').click(function () {
        delAdids = [];
        $('#adxTable > tbody > tr').each(function () {
            var changeClass = $(this).children('td').children('div').attr('class');
            if (changeClass.indexOf('checkboxStyle_change') != -1) {
                //remove td element in tbody
                delAdids.push($(this).find("input[id='adid']").val());
                $(this).remove();
            }
        });
        return false;
    });

    $("#selectOperatorDiv input[type='checkbox']").each(function () {
        var obj = $(this);
        var ids = parent.$("#input_selectOperator").val().split(",");
        for (var i = 0, l = ids.length; i < l; i++) {
            if (obj.attr("id") == ids[i]) {
                obj.attr('checked', true);
            }
        }
    });

    $("#selectOperatorPlaceDiv input[type='checkbox'],#selectPlaceDiv input[type='checkbox'],#selectPlaceClassDiv input[type='checkbox']").each(function () {
        var obj = $(this);
        var ids = parent.$("#selectPlaces").val().split(",");
        for (var i = 1, l = ids.length; i < l; i++) {
            if (obj.val() == ids[i]) {
                obj.attr('checked', true);
            }
        }
    });

    //
    $("#selectOrderDiv input[type='checkbox']").each(function () {
        var obj = $(this);
        var ids = parent.$("#selectPlaces").val().split(",");
        for (var i = 1, l = ids.length; i < l; i++) {
            if (obj.val() == ids[i]) {
                obj.attr('checked', true);
            }
        }
    });

    // 分页中超链接跳转
    $('#selectOperatorPlaceForm .pagination ul li a[href]').click(function () {
        var _page = $(this).attr('href').substr(1);
        $('#selectOperatorPlaceForm').find('input:hidden[name="page"]').val(_page);
        $('#selectOperatorPlaceForm').find('input:hidden[name="operatorId"]').val(parent.$("#input_selectOperator").val());
        $('#selectOperatorPlaceForm').submit();
    });

    // 分页中超链接跳转
    $('#selectPlaceForm .pagination ul li a[href]').click(function () {
        var _page = $(this).attr('href').substr(1);
        $('#selectPlaceForm').find('input:hidden[name="page"]').val(_page);
        $('#selectPlaceForm').find('input:hidden[name="operatorId"]').val(parent.$("#input_selectOperator").val());
        $('#selectPlaceForm').submit();
    });

    // 分页中超链接跳转
    $('#selectPlaceClassForm .pagination ul li a[href]').click(function () {
        var _page = $(this).attr('href').substr(1);
        $('#selectPlaceClassForm').find('input:hidden[name="page"]').val(_page);
        $('#selectPlaceClassForm').find('input:hidden[name="operatorId"]').val(parent.$("#input_selectOperator").val());
        $('#selectPlaceClassForm').submit();
    });

    // 全选
    $('#selectOperatorAll,#selectOperatorPlaceAll,#selectPlaceAll,#selectPlaceClassAll').click(function () {
        $(".input-radiosDiv input[type='checkbox']").attr("checked", true);
        return false;
    });

    // 全不选
    $('#notselectOperatorAll,#notselectOperatorPlaceAll,#notselectPlaceAll,#notselectPlaceClassAll').click(function () {
        $(".input-radiosDiv input[type='checkbox']").attr("checked", false);
        return false;
    });

    //获取省份信息
    if ($("#main_cnul").html()) {
        $("#cn_son_ul").hide();
        if ($("#cn").val() == "省") {
            $("#cn").val("");
        }
        $("#cn_son_ul").append("<li value=''>省</li>");
        var url = "cn";
        $.getJSON(url, function (data) {
            var data_1 = data.province;
            $.each(data_1, function (key, val) {
                $("#cn_son_ul").append('<li>' + val + '</li>');
            });
        });
        $("#cnul_span").on("click", function () {
            if ($('#cn_son_ul').height() > 210) {
                $('#cn_son_ul').addClass("son_ul_change");
            }
            $('#cn_son_ul').show(); //ul显示
        });
        $("ul#cn_son_ul li").live("click", function () {
            $("#cnul_span").text($(this).text());
            if ($(this).text() == "省") {
                $("#cn").val("");
            } else {
                $("#cn").val($(this).text());
            }
            $("#cnCity").val("");
            $("#cnCityul_span").text("市");
            $("#cn_son_ul").hide(); //ul隐藏
        });

        $("#cnul_box").mouseleave(function () {
            $('#cn_son_ul').hide(); //ul隐藏
            $('#cn_son_ul').removeClass("son_ul_showchange");
        });
    }

    //获取省份对应的城市信息
    if ($("#main_cnCityul").html()) {
        $("#cnCityul_son_ul").hide();
        if ($("#cnCity").val() == "市") {
            $("#cnCity").val("");
        }
        $("#cnCityul_span").on("click", function () {
            initSelectUlDataPost("cnCityul_son_ul", "市", "city", $("#cn").val(), "cnCityul_box", "city");
        });
        $('ul#cnCityul_son_ul li').live("click", function () {
            $("#cnCityul_span").text($(this).text());
            if ($(this).text() == "市") {
                $("#cnCity").val("");
            } else {
                $("#cnCity").val($(this).text());
            }
            $("#cnCityul_son_ul").hide(); //ul隐藏
        });
    }

    //动态添加或删除table column
    $('#mediaAdd').click(function () {
        var websitename = $('#s2id_websiteId').find('span').html(); // 获取APP名称
        var adname = $('#s2id_adid').find('span').html(); // 获取广告位名称
        var deviceType = $('#deviceType').val();
        var adID = null;
        var price = null;
        var ctr = null;
        if (websitename == "") {
            alert('请选择网站');
            return false;
        }
        if (adname == '') {
            alert('请选择广告位');
            return false;
        }
        $('#adid option').each(function (i, item) {  // 获取广告位名称的ID
            if (adname === $(item).html()) {
                adID = $(item).val();
                price = $(item).attr('price');
                ctr = $(item).attr('ctr');
            }
        });
        $('#mediaTable tbody').append(
                '<tr class="tbodyTr"><td class="tbodyTd" style="width:5%;"><div class="checkboxStyleTd"></div></td>'
                + '<td class="tbodyTd" style="width:5%;">' + adID + '</td>'
                + '<td class="tbodyTd" style="width:23%;" id="websiteName">' + websitename + '</td>'
                + '<td class="tbodyTd" style="width:23%;" id="adName">' + adname + '</td>'
                + '<td class="tbodyTd" style="width:24%;" id="price">' + price + '</td>'
                + '<td class="tbodyTd" style="width:20%;" id="ctr">' + ctr + '</td>'
                + '<input type="hidden" id="adid" value="' + adID + '" />'
                + '</tr>');
        return false;
    });

    //批量添加过滤非法字符
    $('#id-array').change(function () {
        $('#id-array').val($('#id-array').val().replace(/[^0-9，,]/g, '').replace(/，/g, ','));
    });

    $('#adxAdd').click(function () {
        var appname = $('#s2id_adxId').find('span').html(); // 获取APP名称
        var adname = $('#s2id_adxList').find('span').html(); // 获取广告位名称
        var adID = null;
        var orderid = null;
        $('#adxList option').each(function (i, item) {  // 获取广告位名称的ID
            if (adname === $(item).html()) {
                adID = $(item).val();
                price = $(item).attr('price');
            }
        });
        if (appname == "") {
            alert('请选择APP名称');
            return false;
        }
        if (adname == '') {
            alert('请选择广告位');
            return false;
        }
        $('#adxTable tbody').append(
            '<tr class="tbodyTr"><td class="tbodyTd" style="width:5%;"><div class="checkboxStyleTd"></div></td>'
            + '<td class="tbodyTd" style="width:5%;">' + adID + '</td>'
            + '<td class="tbodyTd" style="width:30%;" id="appName">' + appname + '</td>'
            + '<td class="tbodyTd" style="width:30%;" id="adName">' + adname + '</td>'
            + '<td class="tbodyTd" style="width:30%;" id="price">' + price + '</td>'
            + '<input type="hidden" id="adid" value="' + adID + '" />'
            + '</tr>');
        return false;
    });

    $('#websiteId').trigger("change");
    $('#adxId').trigger("change");
});

function initSelectUlData(target_sonulId, defaultName, url, paramValue, boxName, tabId) {
    $("#" + target_sonulId).empty();
    $("#" + target_sonulId).append("<li value=''>" + defaultName + "</li>");
    if (paramValue != -1 && paramValue != "") {
        $.getJSON(url, function (data) {
            var data_1 = data[tabId];
            $.each(data_1, function (key, val) {
                $("#" + target_sonulId).append('<li>' + val + '</li>');
            });
            $("#" + target_sonulId).show(); //ul显示
            if ($("#" + target_sonulId).height() > 210) {
                $("#" + target_sonulId).addClass("son_ul_change");
            }
        });
    } else {
        $("#" + target_sonulId).show();
    }
    $("#" + boxName).mouseleave(function () {
        $("#" + target_sonulId).hide(); //ul隐藏
        $("#" + target_sonulId).removeClass("son_ul_change");
    });
}

//批量添加媒体
function mediaAddBulk(deviceType, mode, price) {
    var ctx = $('#ctx').val();
    var idArray = $('#id-array').val();
    if(idArray ==''||idArray=='undefined'){
        alert('请填写广告位id');
        return;
    }
    $.ajax({
        type: "get",
        url: ctx + "/advertiser/main/ad/target/ad-group-alloperator/getAds",
        data: {
            "websiteId": "",
            "idArray": idArray,
            "deviceType": deviceType,
            "mode": mode,
            "price": price
        },
        dataType: "json",
        success: function (res) {
            if (res.status == "OK") {
                res.data.data.forEach(function (item) {
                    $('#mediaTable tbody').append(
                        '<tr class="tbodyTr"><td class="tbodyTd" style="width:5%;"><div class="checkboxStyleTd"></div></td>'
                        + '<td class="tbodyTd" style="width:5%;">' + item.id + '</td>'
                        + '<td class="tbodyTd" style="width:23%;" id="websiteName">' + item.mediaName + '</td>'
                        + '<td class="tbodyTd" style="width:23%;" id="adName">' + item.name + '</td>'
                        + '<td class="tbodyTd" style="width:24%;" id="price">' + item.price + '</td>'
                        + '<td class="tbodyTd" style="width:20%;" id="ctr">' + item.ctr + '</td>'
                        + '<input type="hidden" id="adid" value="' + item.id + '" />'
                        + '</tr>');
                });
            } else {
                alert("批量添加失败:" + res.msg);
            }
        },
        error: function () {
            alert("系统错误，请联系管理员");
        }
    });
}

//批量添加adx
function adxAddBulk(mode, price) {
    var ctx = $('#ctx').val();
    var idArray = $('#id-array').val();
    $.ajax({
        type: "get",
        url: ctx + "/advertiser/main/ad/target/ad-group-alloperator/getAdxAds",
        data: {
            "appId": "",
            "idArray": idArray,
            "mode": mode,
            "price": price
        },
        dataType: "json",
        success: function (res) {
            if (res.status == "OK") {
                res.data.data.forEach(function (item) {
                    $('#adxTable tbody').append(
                        '<tr class="tbodyTr"><td class="tbodyTd" style="width:5%;"><div class="checkboxStyleTd"></div></td>'
                        + '<td class="tbodyTd" style="width:5%;">' + item.id + '</td>'
                        + '<td class="tbodyTd" style="width:30%;" id="appName">' + item.mediaName + '</td>'
                        + '<td class="tbodyTd" style="width:30%;" id="adName">' + item.name + '</td>'
                        + '<td class="tbodyTd" style="width:30%;" id="price">' + item.price + '</td>'
                        + '<input type="hidden" id="adid" value="' + item.id + '" />'
                        + '</tr>');
                });
            } else {
                alert("批量添加失败:" + res.msg);
            }
        },
        error: function () {
            alert("系统错误，请联系管理员");
        }
    });
}

function websiteIdChange(websiteId, deviceType, mode, price) {
    var ctx = $('#ctx').val();
    $.ajax({
        type: "get",
        url: ctx + "/advertiser/main/ad/target/ad-group-alloperator/getAds",
        data: {
            "websiteId": websiteId,
            "idArray": "",
            "deviceType": deviceType,
            "mode": mode,
            "price": price
        },
        dataType: "json",
        success: function (data) {
            if (data.status == "OK") {
                $("#adid").empty();
                var resultMap = data.data;
                var result = resultMap.data;
                if (result.length > 0) {
                    var html = "<option value=''>--请选择--</option>";
                    for (var i = 0; i < result.length; i++) {
                        var ads = result[i];
                        html += "<option value='" + ads.id + "' price='" + ads.price + "'ctr='" + ads.ctr+ "'>" + ads.name + "</option>";
                    }
                    $("#adid").append(html);
                } else {
                    $("#adid").append("没有高于设置单价的广告位");
                }
                $("#adid").select2();
            } else {
                alert("查询广告位失败:" + data.msg);
            }
        },
        error: function () {
            alert("系统错误，请联系管理员");
        }
    });
}

function adxIdChange(appId, mode, price) {
    var ctx = $('#ctx').val();
    $.ajax({
        type: "get",
        url: ctx + "/advertiser/main/ad/target/ad-group-alloperator/getAdxAds",
        data: {
            "appId": appId,
            "idArray": "",
            "mode": mode,
            "price": price
        },
        dataType: "json",
        success: function (data) {
            if (data.status == "OK") {
                var resultMap = data.data;
                var result = resultMap.data;
                $("#adxList").empty();
                if (result.length > 0) {
                    var html = "<option value=''>--请选择--</option>";
                    for (var i = 0; i < result.length; i++) {
                        var ads = result[i];
                        html += "<option value='" + ads.id + "' price='" + ads.price + "'>" + ads.name + "</option>";
                    }
                    $("#adxList").append(html);
                }
                $("#adxList").select2();
            } else {
                alert("查询广告位失败:" + data.msg);
            }
        },
        error: function () {
            alert("系统错误，请联系管理员");
        }
    });
}


function initSelectUlDataPost(target_sonulId, defaultName, url, paramValue, boxName, tabId) {
    $("#" + target_sonulId).empty();
    $("#" + target_sonulId).append("<li value=''>" + defaultName + "</li>");
    if (paramValue != -1 && paramValue != "") {
        $.post(url, { province: paramValue }, function (data) {
            var data_1 = data[tabId];
            $.each(data_1, function (key, val) {
                $("#" + target_sonulId).append('<li>' + val + '</li>');
            });
            $("#" + target_sonulId).show(); //ul显示
            if ($("#" + target_sonulId).height() > 210) {
                $("#" + target_sonulId).addClass("son_ul_change");
            }
        });
    } else {
        $("#" + target_sonulId).show();
    }
    $("#" + boxName).mouseleave(function () {
        $("#" + target_sonulId).hide(); //ul隐藏
        $("#" + target_sonulId).removeClass("son_ul_change");
    });
}

function unique(arr) {
    var result = [], hash = {};
    for (var i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem]) {
            result.push(elem);
            hash[elem] = true;
        }
    }
    return result;
}

function categoryIdChange(categoryId,deviceType,mode,price){
    var ctx = $('#ctx').val();
    if(deviceType ==3){
        $.ajax({
            type: "get",
            url: ctx + "/advertiser/main/ad/target/ad-group-alloperator/getSubCategory",
            data: {
                "categoryId": categoryId,
                "deviceType": deviceType
            },
            dataType: "json",
            success: function (data) {
                if (data.status == "OK") {
                    $("#subCategoryId").empty();
                    var resultMap = data.data;
                    var result = resultMap.subCategoryList;
                    if (result.length > 0) {
                        var html = "<option value=''>--请选择--</option>";
                        for (var i = 0; i < result.length; i++) {
                            var category = result[i];
                            html += "<option value=" + category.categoryId + ">" + category.categoryName + "</option>";
                        }
                        $("#subCategoryId").append(html);
                    } else {
                        $("#subCategoryId").append("没有此分类的数据");
                    }
                    $("#subCategoryId").select2();
                } else {
                    alert("查询分类网站失败:" + data.msg);
                }
            },
            error: function () {
                alert("系统错误，请联系管理员");
            }
        });
    }else{
        $.ajax({
            type: "get",
            url: ctx + "/advertiser/main/ad/target/ad-group-alloperator/getWebsite",
            data: {
                "categoryId": categoryId,
                "deviceType": deviceType,
                "mode": mode,
                "price": price
            },
            dataType: "json",
            success: function (data) {
                if (data.status == "OK") {
                    $("#websiteId").empty();
                    var resultMap = data.data;
                    var result = resultMap.data;
                    if (result.length > 0) {
                        var html = "<option value=''>--请选择--</option>";
                        for (var i = 0; i < result.length; i++) {
                            var media = result[i];
                            html += "<option value=" + media.id + ">" + media.name + "</option>";
                        }
                        $("#websiteId").append(html);
                    } else {
                        $("#websiteId").append("没有此分类的数据");
                    }
                    $("#websiteId").select2();
                } else {
                    alert("查询分类网站失败:" + data.msg);
                }
            },
            error: function () {
                alert("系统错误，请联系管理员");
            }
        });
    }
}

function subCategoryIdChange(categoryId,deviceType,mode,price){
    var ctx = $('#ctx').val();
    $.ajax({
        type: "get",
        url: ctx + "/advertiser/main/ad/target/ad-group-alloperator/getWebsite",
        data: {
            "categoryId": categoryId,
            "deviceType": deviceType,
            "mode": mode,
            "price": price
        },
        dataType: "json",
        success: function (data) {
            if (data.status == "OK") {
                $("#websiteId").empty();
                var resultMap = data.data;
                var result = resultMap.data;
                if (result.length > 0) {
                    var html = "<option value=''>--请选择--</option>";
                    for (var i = 0; i < result.length; i++) {
                        var media = result[i];
                        html += "<option value=" + media.id + ">" + media.name + "</option>";
                    }
                    $("#websiteId").append(html);
                } else {
                    $("#websiteId").append("没有此分类的数据");
                }
                $("#websiteId").select2();
            } else {
                alert("查询分类网站失败:" + data.msg);
            }
        },
        error: function () {
            alert("系统错误，请联系管理员");
        }
    });
}